﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Runtime.InteropServices;
using mshtml;
//using SHDocVw;

namespace 学籍网
{
    public partial class Form1 : Form
    {
        //verifyCode.dll是由x86平台下的，所以软件需编译为x86，如果编译为x64或any cpu则在调用该dll时会出现异常：试图加载格式不正确的程序。 (异常来自 HRESULT:0x8007000B)
        [DllImport("verifyCode.dll", EntryPoint = "getGZXJCode")]
        static extern string getGZXJCode(string imgFile);
        [DllImport("verifyCode.dll", EntryPoint = "getGDXJCode")]
        static extern string getGDXJCode(string imgFile);

        /// <summary>
        /// 将本库支持读取的图像文件转换为24位的BMP文件。成功返回 1 ，失败返回一个小于等于零的数值，具体为： 0: 未知错误； -1: 文件不存在； -2: 系统资源不足； -3: 该文件格式不被支持； -4: 编码时出错； -6: 编码时系统资源不足； -7: 编码参数错误。 目前可以读取如下源格式的图像并转换到BMP格式：标准JPEG（全部格式）、BMP（目前仅支持24位BMP）、TIFF（单页图像所有格式）、PNG（32位及32位以下）、PCX（8位和24位，RLE压缩）、PCD（取第三幅）。
        /// </summary>
        /// <param name="imgFile">源文件</param>
        /// <param name="bmpFile">目标文件</param>
        /// <returns></returns>
        [DllImport("verifyCode.dll", EntryPoint = "img2bmp")]
        static extern int img2bmp(string imgFile, string bmpFile);

        private int autoLoginGZXJ = 0;
        private int autoLoginGDXJ = 0;

        public Form1()
        {
            InitializeComponent();
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            try
            {
                System.Diagnostics.Debug.WriteLine(webBrowser_gzxj.Url.ToString());
                System.Diagnostics.Debug.WriteLine(autoLoginGZXJ);
                if(string.IsNullOrEmpty(textBox_gzxj_name.Text.Trim()) || string.IsNullOrEmpty(textBox_gzxj_pw.Text.Trim()))
                {
                    return;
                }
                if (webBrowser_gzxj.Url.ToString() == "http://www.gzeducms.cn/login.jsp")
                {
                //getcode:
                    HtmlElement uid = webBrowser_gzxj.Document.GetElementById("uid");
                    HtmlElement upw = webBrowser_gzxj.Document.GetElementById("upw");
                    if (uid != null) uid.SetAttribute("value", textBox_gzxj_name.Text.Trim());//输入用户名
                    else return;
                    if (upw != null) upw.SetAttribute("value", textBox_gzxj_pw.Text.Trim());//输入密码
                    else return;

                    HtmlElement inputCaptcha = webBrowser_gzxj.Document.GetElementById("captcha");
                    HtmlElement captchaImg = null;
                    foreach (HtmlElement eleImg in webBrowser_gzxj.Document.Images)
                    {
                        if (eleImg.GetAttribute("src").IndexOf("ValidateImage") > 0)
                        {
                            captchaImg = eleImg;
                            break;
                        }
                    }
                    if (captchaImg == null) return;
                    string code = getCaptchaStr(webBrowser_gzxj, captchaImg, true);//自动识别验证码
                    if (string.IsNullOrEmpty(code)) code = getCaptchaStr(webBrowser_gzxj, captchaImg, true);
                    inputCaptcha.SetAttribute("value", code);//输入验证码
                    webBrowser_gzxj.Document.InvokeScript("sys_login");//执行登录//webBrowser1.Document.InvokeScript ( "add", new object[] { 1, 2 } );
                    //webBrowser1.Navigate("javascript:sys_login();");//执行登录
                    System.Diagnostics.Debug.WriteLine("gzxj login");
                    //Application.DoEvents();
                    //System.Threading.Thread.Sleep(1000);
                    //Application.DoEvents();
                    DateTime current = DateTime.Now.AddMilliseconds(2000);
                    while (current > DateTime.Now)
                    {
                        Application.DoEvents();//转让控制权  
                        System.Threading.Thread.Sleep(100);
                    }
                    /*
                    button_login_gzxj_Click(sender, e);*/

                    autoLoginGZXJ++;
                    System.Diagnostics.Debug.WriteLine(autoLoginGZXJ);

                    HtmlElement loginMsg = webBrowser_gzxj.Document.GetElementById("login_warningMsg");
                    if ((loginMsg != null) && (loginMsg.InnerText.IndexOf("登录") < 0) && (autoLoginGZXJ < 5))//超过5次没有自动登录成功则不再自动登录
                    {
                        webBrowser_gzxj.Url = new Uri("http://www.gzeducms.cn");
                        System.Diagnostics.Debug.WriteLine("没正确登录，刷新页面");
                        return;
                    }
                    if (autoLoginGZXJ >= 5) MessageBox.Show("auto login gzxj fail");
                    autoLoginGZXJ = 0;
                    //点击登录按钮：
                    /*HtmlElementCollection eleCollection = webBrowser1.Document.GetElementsByTagName("img");
                    foreach(HtmlElement ele in eleCollection)
                    {
                        System.Diagnostics.Debug.WriteLine(ele.GetAttribute("src"));
                        if (ele.GetAttribute("src") == "http://www.gzeducms.cn/images/btn_login.gif")
                        {
                            ele.InvokeMember("click");
                            System.Diagnostics.Debug.WriteLine("gzxj click");
                        }
                    }*/
                }
                else
                {
                    autoLoginGZXJ = 0;
                    System.Diagnostics.Debug.WriteLine(autoLoginGZXJ);
                }
                System.Diagnostics.Debug.WriteLine("webBrowser1_DocumentCompleted end");
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message, "auto login gzxj fail");
            }
        }

        private void webBrowser2_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(textBox_gdxj_name.Text.Trim()) || string.IsNullOrEmpty(textBox_gdxj_pw.Text.Trim()))
                {
                    return;
                }
                if (webBrowser_gdxj.Document.Body.OuterHtml.IndexOf("frmLogin") > 0)
                {
                    if (autoLoginGDXJ >= 5)
                    {
                        MessageBox.Show("auto login gdxj fail");
                        return;
                    }
                    //System.Diagnostics.Debug.WriteLine("==============gdxj=================");
                    HtmlElementCollection eleCollection = webBrowser_gdxj.Document.GetElementsByTagName("input");
                    //System.Diagnostics.Debug.WriteLine(eleCollection.Count);
                    foreach (HtmlElement ele in eleCollection)
                    {
                        //System.Diagnostics.Debug.WriteLine(ele.GetAttribute("name"));
                        if (ele.GetAttribute("name") == "_j_username")
                        {//输入用户名
                            ele.SetAttribute("value", textBox_gdxj_name.Text.Trim());
                        }
                        if (ele.GetAttribute("name") == "j_password")
                        {//输入密码
                            ele.SetAttribute("value", textBox_gdxj_pw.Text.Trim());
                        }/*
                        if (ele.GetAttribute("name") == "rdmCode")
                        {//输入验证码
                            ele.SetAttribute("value", "0000");
                        }*/
                    }

                    HtmlElement inputCaptcha = webBrowser_gdxj.Document.GetElementById("rdmCode");
                    //while ((inputCaptcha != null) && (autoLoginGDXJ < 5))//超过5次没有自动登录成功则不再自动登录
                    {
                        HtmlElement captchaImg = webBrowser_gdxj.Document.GetElementById("checkcodeimg");
                        string code = getCaptchaStr(webBrowser_gdxj, captchaImg, false);
                        if (string.IsNullOrEmpty(code)) code = getCaptchaStr(webBrowser_gdxj, captchaImg, false);
                        if (string.IsNullOrEmpty(code)) code = "1234";
                        inputCaptcha.SetAttribute("value", code);//输入验证码
                        webBrowser_gdxj.Document.InvokeScript("doLogin");
                        System.Diagnostics.Debug.WriteLine("gdxj login");
                        autoLoginGDXJ++;
                        System.Diagnostics.Debug.WriteLine(autoLoginGDXJ);
                        Application.DoEvents();
                        System.Threading.Thread.Sleep(1000);
                        Application.DoEvents();
                        //inputCaptcha = webBrowser_gdxj.Document.GetElementById("rdmCode");
                    }
                    //if (autoLoginGZXJ >= 5) MessageBox.Show("auto login gdxj fail");
                    //webBrowser2.Document.InvokeScript("doLogin");//执行登录
                    //webBrowser2.Navigate("javascript:doLogin();");//执行登录
                    System.Diagnostics.Debug.WriteLine("gdxj login");
                    //点击登录按钮：
                    /*eleCollection = webBrowser2.Document.GetElementsByTagName("img");
                    foreach (HtmlElement ele in eleCollection)
                    {
                        System.Diagnostics.Debug.WriteLine(ele.GetAttribute("src"));
                        if (ele.GetAttribute("src") == "http://gdxj.edugd.cn/skins/images/l5/ok.png")
                        {
                            ele.InvokeMember("click");
                            System.Diagnostics.Debug.WriteLine("gdxj login");
                        }
                    }*/
                }
                else
                {
                    if (webBrowser_gdxj.Document.Body.OuterHtml.IndexOf("frmLogin") < 0)
                        autoLoginGDXJ = 0;
                    System.Diagnostics.Debug.WriteLine(autoLoginGDXJ);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "auto login gdxj fail");
            }
        }

        /// <summary>
        /// 自动识别广州学籍网和全国学籍网的验证码
        /// </summary>
        /// <param name="browser"></param>
        /// <param name="imgElement">验证码图片元素</param>
        /// <param name="gz">为真识别广州学籍网验证码，否则识别全国学籍网验证码</param>
        /// <returns></returns>
        private string getCaptchaStr(WebBrowser browser, HtmlElement imgElement, bool gz)
        {
            string imgFile, retStr="";
            if(gz)
                imgFile = Application.StartupPath + "\\captcha_gzxj.bmp";//http://blog.csdn.net/hwt0101/article/details/8250712
            else
                imgFile = Application.StartupPath + "\\captcha_gdxj.bmp";

            try
            {
                HTMLDocument doc = (HTMLDocument)browser.Document.DomDocument;
                HTMLBody body = (HTMLBody)doc.body;
                IHTMLControlRange rang = (IHTMLControlRange)body.createControlRange();
                IHTMLControlElement img = (IHTMLControlElement)(imgElement.DomElement);
                rang.add(img);
                rang.execCommand("Copy", false, null);
                Delay(1000);//稍微延迟一下，否则可能没有复制到导致后面出错
                Clipboard.GetImage().Save(imgFile, System.Drawing.Imaging.ImageFormat.Bmp);

                //int retCode = img2bmp(imgFile, imgFile);
                if(gz)
                    retStr = getGZXJCode(imgFile);
                else
                    retStr = getGDXJCode(imgFile);
            
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
            return retStr;
        }

        /// <summary>
        /// http://blog.163.com/da7_1@126/blog/static/10407267820135795045238/
        /// http://www.cnblogs.com/yuanbao/archive/2007/09/12/890730.html
        /// http://blog.csdn.net/pengxuan/article/details/5922491
        /// http://www.softos.org/?p=353
        /// 获取图像内容
        /// </summary>
        /// <param name="browser">显示图像的浏览器控件</param>
        /// <param name="imgElement">从浏览器中读取到的img</param>
        private static Image GetImage(WebBrowser browser, HtmlElement imgElement)
        {
            HTMLDocument doc = (HTMLDocument)browser.Document.DomDocument;
            HTMLBody body = (HTMLBody)doc.body;
            IHTMLControlRange rang = (IHTMLControlRange)body.createControlRange();
            IHTMLControlElement img = (IHTMLControlElement)(imgElement.DomElement);
            rang.add(img);
            rang.execCommand("Copy", false, null);
            Image regImg = Clipboard.GetImage();
            Clipboard.Clear();
            return regImg;
        }
        
        private void Delay(int Millisecond) //延迟系统时间，但系统又能同时能执行其它任务；
        {
            DateTime current = DateTime.Now.AddMilliseconds(Millisecond);
            while (current > DateTime.Now)
            {
                Application.DoEvents();//转让控制权            
            }
            return;
        }

        //http://www.cnblogs.com/cgli/archive/2011/04/09/2010497.html
        //http://www.cnblogs.com/zhangzhu/p/3408317.html
        //http://blog.163.com/da7_1@126/blog/static/10407267820130258172232/
        #region 同步通过POST方式发送数据
        /// <summary>
        /// 通过POST方式发送数据
        /// http://blog.csdn.net/cctv_hu/article/details/6003005
        /// </summary>
        /// <param name="Url">url</param>
        /// <param name="postDataStr">Post数据</param>
        /// <param name="cookie">Cookie容器</param>
        /// <returns></returns>
        public string SendDataByPost(string Url, string postDataStr, ref CookieContainer cookie)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            if (cookie.Count == 0)
            {
                request.CookieContainer = new CookieContainer();
                cookie = request.CookieContainer;
            }
            else
            {
                request.CookieContainer = cookie;
            }

            request.Method = "POST";
            request.Accept = "*/*";
            request.Headers.Add("Accept-Language:zh-cn");
            request.Referer = @"http://gdxj.edugd.cn/jsp/mems/xjgl/zhcx/qsxscx/qsxscx_list.jsp";
            request.Headers.Add("x-requested-with:XMLHttpRequest");
            request.Headers.Add("Accept-Encoding:gzip, deflate");
            request.Headers.Add("DNT:1");
            request.UserAgent = @"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/6.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; Shuame)";
            //request.Headers.Add("Host:gdxj.edugd.cn");
            request.ContentType = "application/json";
            //request.Headers.Add("Content-Length:" + postDataStr.Length.ToString());
            request.Headers.Add("Cookie:" + CookieHandler.FullWebBrowserCookie.GetCookieInternal(new Uri("http://gdxj.edugd.cn"), true));

            byte[] byte1 = Encoding.GetEncoding("utf-8").GetBytes(postDataStr);
            request.ContentLength = byte1.Length;
            Stream myRequestStream = request.GetRequestStream();
            myRequestStream.Write(byte1, 0, byte1.Length);
            myRequestStream.Close();
            /*StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("utf-8"));
            myStreamWriter.Write(postDataStr);
            myStreamWriter.Close();*/

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            //System.Diagnostics.Debug.WriteLine(request.Headers.Get("Set-Cookie"));
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }
        #endregion

        #region 同步通过GET方式发送数据
        /// <summary>
        /// 通过GET方式发送数据
        /// </summary>
        /// <param name="Url">url</param>
        /// <param name="postDataStr">GET数据</param>
        /// <param name="cookie">GET容器</param>
        /// <returns></returns>
        public string SendDataByGET(string Url, string postDataStr="", CookieContainer cookie=null)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
            if (cookie != null)
            {
                request.CookieContainer = cookie;
            }

            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }
        #endregion

        private void 进入学籍网站ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if(tabControl1.SelectedIndex==0)
            {
                webBrowser_gzxj.Url = new Uri("http://www.gzeducms.cn");
            }
            else if(tabControl1.SelectedIndex==1)
            {
                webBrowser_gdxj.Url = new Uri("http://gdxj.edugd.cn");
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //tabControl1.SelectedIndex = 1;

            //获取软件版本、软件生成时间
            toolStripStatusLabel_version.Text = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString() + " ";
            DateTime buildTime = System.IO.File.GetLastWriteTime(this.GetType().Assembly.Location);
            toolStripStatusLabel_buildTime.Text = buildTime.ToLongDateString() + " " + buildTime.ToLongTimeString();
            //从网上获取最新版本信息：http://git.oschina.net/wooddoor/ChaiMen_XueJiTool/raw/master/%E5%AD%A6%E7%B1%8D%E7%BD%91/bin/Release/NewestVersion.txt
            backgroundWorker1.RunWorkerAsync();

            //读取配置文件
            textBox_gzxj_name.Text = HexString.HexStringToString(XmlConfig.GetConfigData("gzxj_name", string.Empty), Encoding.UTF8);
            textBox_gzxj_pw.Text = HexString.HexStringToString(XmlConfig.GetConfigData("gzxj_pw", string.Empty), Encoding.UTF8);
            textBox_gdxj_name.Text = HexString.HexStringToString(XmlConfig.GetConfigData("gdxj_name", string.Empty), Encoding.UTF8);
            textBox_gdxj_pw.Text = HexString.HexStringToString(XmlConfig.GetConfigData("gdxj_pw", string.Empty), Encoding.UTF8);

            //期望能够SHDocVw.WebBrowser的事件能够获取到ajax，结果无用
            //http://www.cnblogs.com/eaglet/archive/2008/11/19/1336347.html
            //SHDocVw.WebBrowser wb = (SHDocVw.WebBrowser)webBrowser_gzxj.ActiveXInstance;
            //wb.NavigateComplete2 += new SHDocVw.DWebBrowserEvents2_NavigateComplete2EventHandler();
            //wb.BeforeNavigate2 += new SHDocVw.DWebBrowserEvents2_BeforeNavigate2EventHandler(WebBrowser_BeforeNavigate2);

            //期望通过hook wininet拦截ajax，在IE11下无用
            //http://blog.csdn.net/wangjia184/article/details/7250421
            //WininetHookWrapper.SetRequestCompletionCallback(this.OnRequestCompleted);
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            string strNewestVersion = SendDataByGET(@"http://git.oschina.net/wooddoor/ChaiMen_XueJiTool/raw/master/%E5%AD%A6%E7%B1%8D%E7%BD%91/bin/Release/NewestVersion.txt");
            System.Diagnostics.Debug.WriteLine(strNewestVersion);
            toolStripStatusLabel_NewestVersion.Text = strNewestVersion;
        }

        /*private void WebBrowser_BeforeNavigate2(object pDisp, ref object URL, ref object Flags, ref object TargetFrameName, ref object PostData, ref object Headers, ref bool Cancel)
        {
            //无法捕捉的ajax
            System.Diagnostics.Debug.WriteLine("WebBrowser_BeforeNavigate2：" + URL.ToString());
        }

        private void OnRequestCompleted(string verb, string url, string requestHeaders, string responseHeaders, string requestBodyFilename)
        {
            //IE11下hook wininet无法拦截
            System.Diagnostics.Debug.WriteLine("WininetHook：" + url);
        }*/

        private void button_saveConfig_Click(object sender, EventArgs e)
        {
            XmlConfig.WriteConfigData("gzxj_name", HexString.StringToHexString(textBox_gzxj_name.Text.Trim(), Encoding.UTF8));
            XmlConfig.WriteConfigData("gzxj_pw", HexString.StringToHexString(textBox_gzxj_pw.Text.Trim(), Encoding.UTF8));
            XmlConfig.WriteConfigData("gdxj_name", HexString.StringToHexString(textBox_gdxj_name.Text.Trim(), Encoding.UTF8));
            XmlConfig.WriteConfigData("gdxj_pw", HexString.StringToHexString(textBox_gdxj_pw.Text.Trim(), Encoding.UTF8));
            MessageBox.Show("设置保存完毕");
        }

        private void button_login_gzxj_Click(object sender, EventArgs e)
        {
            try
            {
                HtmlElement uid = webBrowser_gzxj.Document.GetElementById("uid");
                HtmlElement upw = webBrowser_gzxj.Document.GetElementById("upw");
                if (uid != null) uid.SetAttribute("value", textBox_gzxj_name.Text.Trim());//输入用户名
                if (upw != null) upw.SetAttribute("value", textBox_gzxj_pw.Text.Trim());//输入密码
                System.Diagnostics.Debug.WriteLine("uid.value：" + uid.GetAttribute("value"));

                HtmlElement captchaImg = null;
                string code = string.Empty;
                foreach (HtmlElement eleImg in webBrowser_gzxj.Document.Images)
                {
                    if (eleImg.GetAttribute("src").IndexOf("ValidateImage") > 0)
                    {
                        captchaImg = eleImg;
                        break;
                    }
                }
                if (captchaImg != null)
                {
                    code = getCaptchaStr(webBrowser_gzxj, captchaImg, true);//自动识别验证码
                    if (string.IsNullOrEmpty(code)) code = getCaptchaStr(webBrowser_gzxj, captchaImg, true);
                    webBrowser_gzxj.Document.GetElementById("captcha").SetAttribute("value", code);//输入验证码
                }

                webBrowser_gzxj.Document.InvokeScript("sys_login");//执行登录//webBrowser1.Document.InvokeScript ( "add", new object[] { 1, 2 } );
                //webBrowser1.Navigate("javascript:sys_login();");//执行登录

                //延时让出时间以登录
                DateTime current = DateTime.Now.AddMilliseconds(2000);
                while (current > DateTime.Now)
                {
                    Application.DoEvents(); 
                    System.Threading.Thread.Sleep(100);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
        }

        private void button_login_gdxj_Click(object sender, EventArgs e)
        {
            HtmlElementCollection eleCollection = webBrowser_gdxj.Document.GetElementsByTagName("input");
            //System.Diagnostics.Debug.WriteLine(eleCollection.Count);
            foreach (HtmlElement ele in eleCollection)
            {
                //System.Diagnostics.Debug.WriteLine(ele.GetAttribute("name"));
                if (ele.GetAttribute("name") == "_j_username")
                {//输入用户名
                    ele.SetAttribute("value", textBox_gdxj_name.Text.Trim());
                }
                if (ele.GetAttribute("name") == "j_password")
                {//输入密码
                    ele.SetAttribute("value", textBox_gdxj_pw.Text.Trim());
                }
            }
            string imgFile = Application.StartupPath + "\\captcha_gdxj.bmp";
            System.Diagnostics.Debug.WriteLine(imgFile);

            HtmlElement inputCaptcha = webBrowser_gdxj.Document.GetElementById("rdmCode");
            HTMLDocument doc = (HTMLDocument)webBrowser_gdxj.Document.DomDocument;
            HTMLBody body = (HTMLBody)doc.body;
            IHTMLControlRange rang = (IHTMLControlRange)body.createControlRange();
            IHTMLControlElement img = (IHTMLControlElement)(webBrowser_gdxj.Document.GetElementById("checkcodeimg").DomElement);
            rang.add(img);
            rang.execCommand("Copy", false, null);
            Delay(500);
            Clipboard.GetImage().Save(imgFile, System.Drawing.Imaging.ImageFormat.Bmp);
            //int retCode = img2bmp(imgFile, imgFile);
            string code = getGDXJCode(imgFile);

            inputCaptcha.SetAttribute("value", code);//输入验证码
            webBrowser_gdxj.Document.InvokeScript("doLogin");
            System.Diagnostics.Debug.WriteLine("gdxj login");
        }

        private void toolStripStatusLabel2_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(toolStripStatusLabel2.Text);
        }

        private void toolStripStatusLabel4_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(toolStripStatusLabel4.Text);
        }

        private void ToolStripMenuItem_GDXJH粘贴_Click(object sender, EventArgs e)
        {
            try
            {
                string excelText = System.Windows.Forms.Clipboard.GetText();
                string[] strArr = excelText.Split(new Char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string str in strArr)
                {
                    string[] data = str.Split(new Char[] { '\t' }, StringSplitOptions.RemoveEmptyEntries);
                    ListViewItem item = new ListViewItem(data[0]);
                    item.SubItems.Add(data[1]);
                    item.SubItems.Add("");
                    listView_GDXJH.Items.Add(item);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void ToolStripMenuItem_GDXJH清空列表_Click(object sender, EventArgs e)
        {
            listView_GDXJH.Items.Clear();
        }

        private void ToolStripMenuItem_GDXJH删除当前选中项_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem item in listView_GDXJH.SelectedItems)
            {
                listView_GDXJH.Items.Remove(item);
            }
        }

        private void button_getGDXJH1_Click(object sender, EventArgs e)
        {
            button_getGDXJH1.Enabled = false;
            try
            {
                CookieContainer cc = getCookieFromWebbrowser(CookieHandler.FullWebBrowserCookie.GetCookieInternal(new Uri("http://gdxj.edugd.cn"), true));
                System.Diagnostics.Debug.WriteLine(webBrowser_gdxj.Document.Cookie);
                System.Diagnostics.Debug.WriteLine(CookieReader.GetCookie(webBrowser_gdxj.Document.Domain));
                System.Diagnostics.Debug.WriteLine(CookieHandler.FullWebBrowserCookie.GetCookieInternal(new Uri("http://gdxj.edugd.cn"), true));
                System.Diagnostics.Debug.WriteLine(webBrowser_gdxj.Document.Domain);
                //return;
                string json;
                foreach (ListViewItem item in listView_GDXJH.Items)
                {
                    System.Diagnostics.Debug.WriteLine("{\"params\":{\"javaClass\":\"org.loushang.next.data.ParameterSet\",\"map\":{\"xm\":\"" + item.SubItems[0].Text + "\",\"sfzjh\":\"" + item.SubItems[1].Text + "\",\"xbm\":\"\",\"csrq\":\"\",\"sfzx\":\"\",\"grbsm\":\"\",\"jdztm\":\"\",\"start\":0,\"limit\":20,\"defaultSort\":{\"javaClass\":\"ArrayList\",\"list\":[]}},\"length\":12},\"context\":{\"javaClass\":\"HashMap\",\"map\":{},\"length\":0}}");
                    json = SendDataByPost(@"http://gdxj.edugd.cn/command/ajax/com.inspur.mems.xsxxgl.cmd.ZxxsXsJbxxQueryCmd/queryQsXs", "{\"params\":{\"javaClass\":\"org.loushang.next.data.ParameterSet\",\"map\":{\"xm\":\"" + (item.SubItems[0].Text) + "\",\"sfzjh\":\"" + item.SubItems[1].Text + "\",\"xbm\":\"\",\"csrq\":\"\",\"sfzx\":\"\",\"grbsm\":\"\",\"jdztm\":\"\",\"start\":0,\"limit\":20,\"defaultSort\":{\"javaClass\":\"ArrayList\",\"list\":[]}},\"length\":12},\"context\":{\"javaClass\":\"HashMap\",\"map\":{},\"length\":0}}", ref cc);
                    System.Diagnostics.Debug.WriteLine(json);
                    System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("\"total\":(\\d),", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                    string total = regex.Match(json).Groups[1].Value;
                    if (string.IsNullOrEmpty(total))
                    {
                        //MessageBox.Show("网络错误");
                        item.SubItems[2].Text = "网络错误";
                    }
                    else if (Int32.Parse(total) > 0)
                    {
                        regex = new System.Text.RegularExpressions.Regex("\"GRBSM\":\"(.{19})\"", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                        string xjh = regex.Match(json).Groups[1].Value;
                        //MessageBox.Show(xjh);
                        item.SubItems[2].Text = xjh;
                    }
                    else
                    {
                        //MessageBox.Show("没找到结果");
                        item.SubItems[2].Text = "没找到结果";
                    }
                    Application.DoEvents();
                    System.Threading.Thread.Sleep(1000);
                }
                MessageBox.Show("end");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            button_getGDXJH1.Enabled = true;
        }

        CookieContainer getCookieFromWebbrowser(WebBrowser wb)
        {
            //在WebBrowser中登录　cookie保存在　WebBrowser.Document.Cookie中
            CookieContainer myCookieContainer = new CookieContainer();

            //String 的Cookie　要转成　Cookie型的　并放入CookieContainer中
            if (wb.Document.Cookie != null)
            {
                string cookieStr = wb.Document.Cookie;
                string[] cookstr = cookieStr.Split(';');
                foreach (string str in cookstr)
                {
                    string[] cookieNameValue = str.Split('=');
                    Cookie ck = new Cookie(cookieNameValue[0].Trim().ToString(), cookieNameValue[1].Trim().ToString());
                    ck.Domain = wb.Document.Domain;//"www.google.com";
                    myCookieContainer.Add(ck);
                }
            }
            return myCookieContainer;
        }

        CookieContainer getCookieFromWebbrowser(string cookieStr)
        {
            //在WebBrowser中登录　cookie保存在　WebBrowser.Document.Cookie中
            CookieContainer myCookieContainer = new CookieContainer();

            //String 的Cookie　要转成　Cookie型的　并放入CookieContainer中
            if (!string.IsNullOrEmpty(cookieStr))
            {
                string[] cookstr = cookieStr.Split(';');
                foreach (string str in cookstr)
                {
                    string[] cookieNameValue = str.Split('=');
                    Cookie ck = new Cookie(cookieNameValue[0].Trim().ToString(), cookieNameValue[1].Trim().ToString());
                    ck.Domain = "gdxj.edugd.cn";
                    myCookieContainer.Add(ck);
                }
            }
            return myCookieContainer;
        }

        private void button_getGDXJH2_Click(object sender, EventArgs e)
        {
            button_getGDXJH2.Enabled = false;
            try
            {
                CookieContainer cc = getCookieFromWebbrowser(CookieHandler.FullWebBrowserCookie.GetCookieInternal(new Uri("http://gdxj.edugd.cn"), true));
                string json = "";
                foreach (ListViewItem item in listView_GDXJH.Items)
                {
                    string[] xjArr = new string[] { "G" + item.SubItems[1].Text, "L" + item.SubItems[1].Text };
                    string xjh = "没找到结果";
                    foreach (string xj in xjArr)
                    {
                        json = SendDataByPost(@"http://gdxj.edugd.cn/command/ajax/com.inspur.mems.xsxxgl.cmd.ZxxsXsJbxxQueryCmd/queryJbxx", "{\"params\":{\"javaClass\":\"org.loushang.next.data.ParameterSet\",\"map\":{\"grbsm\":\"" + xj + "\",\"start\":0,\"limit\":10,\"defaultSort\":{\"javaClass\":\"ArrayList\",\"list\":[]}},\"length\":6},\"context\":{\"javaClass\":\"HashMap\",\"map\":{},\"length\":0}}", ref cc);
                        System.Diagnostics.Debug.WriteLine(json);
                        System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("\"javaClass\":\"DataSet\",\"success\":true,", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                        if (regex.IsMatch(json))
                        {
                            regex = new System.Text.RegularExpressions.Regex("\"GRBSM\":\"(.{19})\"", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                            if (regex.IsMatch(json))
                            {
                                xjh = regex.Match(json).Groups[1].Value;
                                break;
                            }
                        }
                        else
                        {
                            xjh = "网络错误";
                        }
                        Application.DoEvents();
                        System.Threading.Thread.Sleep(1000);
                    }
                    item.SubItems[2].Text = xjh;

                    Application.DoEvents();
                    System.Threading.Thread.Sleep(1000);
                }
                MessageBox.Show("end");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            button_getGDXJH2.Enabled = true;
        }

        private void button_exportGDXJH_Click(object sender, EventArgs e)
        {
            button_exportGDXJH.Enabled = false;
            try
            {
                if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    StringBuilder sb = new StringBuilder();
                    sb.Append("姓名\t身份证\t全国学籍号\r\n");
                    foreach (ListViewItem item in listView_GDXJH.Items)
                    {
                        sb.Append(item.SubItems[0].Text + "\t\'" + item.SubItems[1].Text + "\t" + item.SubItems[2].Text + "\r\n");
                    }
                    FileStream fs = new FileStream(saveFileDialog1.FileName, FileMode.Create);
                    StreamWriter sw = new StreamWriter(fs, Encoding.Default);
                    sw.Write(sb.ToString());
                    sw.Close();
                    fs.Close();
                    MessageBox.Show("END");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            button_exportGDXJH.Enabled = true;
        }

        private void toolStripStatusLabel6_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(toolStripStatusLabel6.Text);
        }

        private void linkLabel4_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start(linkLabel4.Tag.ToString());
        }

        private void linkLabel3_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start(linkLabel3.Tag.ToString());
        }

        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start(linkLabel2.Text);
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start(linkLabel1.Text);
        }
                        
    }
}
